const { DataTypes, UUIDV4 } = require('sequelize');
const sequelize = require('../config/db');
const bcrypt = require('bcryptjs');

const Reader = sequelize.define('Reader', {
  reader_id: {
    type: DataTypes.STRING(36),
    primaryKey: true,
    defaultValue: UUIDV4
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false
  },
  role: {
    type: DataTypes.ENUM('reader', 'author', 'admin'),
    allowNull: false,
    defaultValue: 'reader'
  },
  name: {
    type: DataTypes.STRING
  },
  phone: {
    type: DataTypes.STRING
  },
  email: {
    type: DataTypes.STRING
  },
  address: {
    type: DataTypes.TEXT
  },
  avatar: {
      type: DataTypes.STRING,
      defaultValue: '/files/default_avatar.png'
    },
  introduction: {
    type: DataTypes.TEXT
  }
}, {
  tableName: 'reader',
  timestamps: true,
  createdAt: 'create_at',
  updatedAt: 'update_at'
});

Reader.beforeCreate(async (reader) => {
  if (reader.password) {
    const salt = await bcrypt.genSalt(10);
    reader.password = await bcrypt.hash(reader.password, salt);
  }
});

module.exports = Reader;